package cn.itsource.basic.interceptor;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.Payload;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.jwt.UserInfo;
import cn.itsource.system.mapper.PermissionMapper;
import cn.itsource.user.domain.Logininfo;
import com.mysql.jdbc.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String publicKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求中拿到U-TOKEN
        String token = request.getHeader("U-TOKEN");
        //判断token不是null
        if(token != null){
            //获取到的token去Redis中查询
//            Object logininfo = redisTemplate.opsForValue().get(token);

            //获取公钥
            PublicKey publicKeyPath = RsaUtils
                    .getPublicKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(publicKey)));
            //获取载荷数据
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, publicKeyPath, UserInfo.class);
            //从载荷中获取到用户信息
            UserInfo userInfo = payLoad.getUserInfo();
            //从userInfo中获取用户登录信息
            Logininfo logininfo = userInfo.getLogininfo();

            //若果查询到就放行 并且刷新有效时间30分钟
            if(logininfo != null){
                //校验你是主站用户还是后端管理系统的员工
                Logininfo li = (Logininfo)logininfo;
                if(li.getType() == 0){
                //如果是后端管理系统的员工就需要校验你是否有访问某个url的权限
                    //拿到用户访问的接口方法
                    HandlerMethod method = (HandlerMethod)handler;
                    //判断方法上是否有自定义注解
                    PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                    if(preAuthorize != null){
                        //如果有，拿到该主机的value的值（即sn）
                        String value = preAuthorize.value();

                        //查询该用户自己所拥有的permission 的sn集合
                        List<String> sns = userInfo.getPermissions();

                        //判断该用户拥有的sn集合中是否包含自定义注解的value
                        if(!sns.contains(value)){
                            //不包含返回前端"{\"success\":false,\"resultObj\":\"nopermission\"}"
                            response.setContentType("application/json; charset=UTF-8");
                            response.setCharacterEncoding("utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"nopermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //没查到就拦截 通过响应对象返回{"success":false,"message":"noLogin"}
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"nologin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
